<template>
  <div class="customer-service-container">
    <div class="service-layout">
      <!-- 左侧用户列表 -->
      <div class="user-list">
        <div class="user-list-header">
          <h3>在线用户</h3>
          <el-button type="primary" link @click="refreshUserList">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
        <div class="user-list-content">
          <div v-for="user in onlineUsers" 
               :key="user" 
               :class="['user-item', { active: currentUser === user }]"
               @click="selectUser(user)">
            <el-avatar :size="40">{{ user.charAt(0).toUpperCase() }}</el-avatar>
            <span class="username">{{ user }}</span>
          </div>
          <div v-if="onlineUsers.length === 0" class="no-users">
            暂无在线用户
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div class="chat-header">
          <h2>{{ currentUser ? `与 ${currentUser} 的对话` : '请选择用户' }}</h2>
          <span class="status" :class="{ 'online': isConnected }">
            {{ isConnected ? '在线' : '离线' }}
          </span>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageList">
          <div v-for="(msg, index) in messages" :key="index" 
               :class="['message', msg.sender === 'admin' ? 'sent' : 'received']">
            <div class="message-content">
              <div class="message-header">
                <span class="sender">{{ msg.sender }}</span>
                <span class="time">{{ msg.time }}</span>
              </div>
              <div class="text">{{ msg.content }}</div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入消息..."
            :disabled="!currentUser"
            @keyup.enter.ctrl="handleSendMessage"
          />
          <div class="input-tools">
            <span class="tip">按 Ctrl + Enter 发送</span>
            <el-button 
              type="primary" 
              :disabled="!currentUser || !inputMessage.trim()"
              @click="handleSendMessage"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { initWebSocket, sendMessage, closeWebSocket, getConnectionState, getHistoryMessages } from '@/api/customer'

const onlineUsers = ref([])
const currentUser = ref('')
const messages = ref([])
const inputMessage = ref('')
const messageList = ref(null)
const isConnected = ref(false)

// 时间格式化函数
const formatTime = (date) => {
  if (!(date instanceof Date)) date = new Date(date)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 加载历史消息
const loadHistoryMessages = async (user) => {
  try {
    const response = await getHistoryMessages('admin', user)
    if (response && Array.isArray(response)) {
      messages.value = response.map(msg => {
        const msgTime = msg.createTime ? new Date(msg.createTime) : new Date()
        return {
          type: 'MESSAGE',
          content: msg.content,
          sender: msg.sender,
          toName: msg.receiver,
          time: formatTime(msgTime), // 时间
          timestamp: msgTime.getTime() // 时间戳
        }
      })
      // .sort((a, b) => a.timestamp - b.timestamp)
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    ElMessage.error('加载历史消息失败')
  }
}

// 处理接收到的消息
const handleMessage = (message) => {
  switch (message.type) {
    case 'MESSAGE':
      if (message.sender === currentUser.value || message.toName === currentUser.value) {
        const msgTime = message.createTime ? new Date(message.createTime) : new Date()
        message.time = formatTime(msgTime)
        messages.value.push(message)
        scrollToBottom()
      }
      break
    case 'ONLINE_USERS':
      onlineUsers.value = JSON.parse(message.content)
      break
    case 'SYSTEM':
      ElMessage.info(message.content)
      if (message.content.includes('上线') || message.content.includes('下线')) {
        refreshUserList()
      }
      break
  }
}

// 选择用户
const selectUser = async (user) => {
  currentUser.value = user
  messages.value = [] // 清空消息列表
  await loadHistoryMessages(user)
}

// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || !currentUser.value) {
    return
  }
  const message = {
    type: 'MESSAGE',
    content: inputMessage.value,
    toName: currentUser.value,
    sender: 'admin'
    // 不加time字段，等WebSocket回包
  }
  if (sendMessage(message)) {
    inputMessage.value = ''
    // 发送后立即刷新历史消息
    await loadHistoryMessages(currentUser.value)
  } else {
    ElMessage.error('连接已断开，请刷新页面重试')
  }
}

// 刷新用户列表
const refreshUserList = () => {
  sendMessage({ type: 'GET_ONLINE_USERS' })
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

// 检查连接状态
const checkConnection = () => {
  isConnected.value = getConnectionState() === 'OPEN'
}

onMounted(() => {
  initWebSocket(handleMessage)
  // 定期检查连接状态
  const interval = setInterval(checkConnection, 5000) // 5秒检查一次
  onUnmounted(() => {
    clearInterval(interval) // 卸载时清除定时器
  })
})

onUnmounted(() => {
  closeWebSocket() // 卸载时关闭WebSocket
})
</script>

<style scoped>
.customer-service-container {
  padding: 20px;
  height: calc(100vh - 60px);
  background: #f5f7fa;
}

.service-layout {
  display: flex;
  gap: 20px;
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-list {
  width: 280px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.user-list-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-list-header h3 {
  margin: 0;
  color: #2c3e50;
}

.user-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-item:hover {
  background: #f5f7fa;
}

.user-item.active {
  background: #ecf5ff;
}

.username {
  font-size: 14px;
  color: #2c3e50;
}

.no-users {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  background: #f56c6c;
  color: white;
}

.status.online {
  background: #67c23a;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message.sent {
  align-self: flex-end;
}

.message.received {
  align-self: flex-start;
}

.message-content {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.message.sent .message-content {
  background: #4CAF50;
  color: white;
}

.message.received .message-content {
  background: #f0f0f0;
  color: #333;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.sender {
  font-size: 12px;
  color: #666;
}

.time {
  font-size: 12px;
  color: #666;
}

.message.sent .sender {
  color: rgba(255, 255, 255, 0.8);
}

.message.received .sender {
  color: rgba(0, 0, 0, 0.8);
}

.message.sent .time {
  color: rgba(255, 255, 255, 0.8);
}

.text {
  word-break: break-word;
  line-height: 1.5;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #eee;
  background: white;
}

.input-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.tip {
  color: #999;
  font-size: 12px;
}

@media (max-width: 768px) {
  .service-layout {
    flex-direction: column;
  }

  .user-list {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .message {
    max-width: 85%;
  }
}
</style> 